"""
Created on 2024/8/22 下午4:27
@author:刘飞
@description:
# 城市联动
到乡级 使用方法
1. https://www.npmjs.com/package/china-division 下载数据，把对应的json放入对应目录
2. 修改此文件中对应json名
3. 执行python manage.py init_area 进行数据初始化
"""
import os
import json
import logging
from pathlib import Path
from django.db import transaction
import pypinyin
from django.core.management import BaseCommand
from yc_django_mrbac.models import Area

logger = logging.getLogger(__name__)

"""数据文件所在目录路径"""
DATA_DIR = Path(__file__).resolve().parent.parent.parent


# 递归处理地区数据
@transaction.atomic
def process_areas(data, parent=None, level=1):
    if level > 4:
        level = 4
    for item in data:
        code = item.get('code')
        name = item.get('name')
        pinyin = ''.join([''.join(i) for i in pypinyin.pinyin(name, style=pypinyin.NORMAL)])
        initials = pinyin[0].upper() if pinyin else "#"
        # 根据code判断是否已经存在
        try:
            area = Area.objects.get(code=code)
            area.name = name
            area.level = level
            area.pinyin = pinyin
            area.initials = initials
            area.save()
        except Area.DoesNotExist:
            if parent is None:
                area = Area.add_root(
                    code=code,
                    name=name,
                    level=level,
                    pinyin=pinyin,
                    initials=initials
                )
            else:
                area = parent.add_child(
                    code=code,
                    name=name,
                    level=level,
                    pinyin=pinyin,
                    initials=initials
                )

        if 'children' in item:
            process_areas(item['children'], parent=area, level=level + 1)


def main():
    with open(os.path.join(DATA_DIR, 'data', 'pca-code.json'), 'r',
              encoding="utf-8") as load_f:
        code_list = json.load(load_f)
    process_areas(code_list)


class Command(BaseCommand):
    """
    项目初始化命令: python manage.py init_area
    """

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        logger.info(f"正在准备初始化省份数据...")
        main()
        logger.info("省份数据初始化数据完成！")
